﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TracyGUI.UIComponent;
using Tracy.DataModel;
using System.ComponentModel;
using Tracy;
using Tracy.Messages;
using Tracy.Handlers;
using SharedLib.MessageFramework;
using System.IO;
using SharedLib.Helpers;
using System.Drawing;

namespace TracyGUI
{
    public partial class FormMain
    {
        Button _btnTagAdd;
        ComboBox _cbTagCategory;
        ComboBox _cbTagValue;
        Tag _editingTag = null;
        private FlowLayoutPanel TagPanel
        {
            get
            {
                if (_selectedEntryPage != null)
                {
                    return _selectedEntryPage.TagPanel;
                }
                return null;
            }
        }

        private void InitTagPanel()
        {
            _btnTagAdd = new Button();
            _btnTagAdd.Text = "Add";
            _btnTagAdd.Click += new EventHandler(_btnAdd_Click);

            _cbTagCategory = new ComboBox();
            _cbTagCategory.SelectedIndexChanged += new EventHandler(_cbCategory_SelectedIndexChanged);

            _cbTagValue = new ComboBox();
            _cbTagValue.AutoCompleteSource = AutoCompleteSource.ListItems;
            _cbTagValue.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            _cbTagValue.KeyUp += new KeyEventHandler(_cbValue_KeyUp);
        }

        void _cbValue_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                foreach (string existingValue in _cbTagValue.Items)
                {
                    if (String.Equals(existingValue, _cbTagValue.Text, StringComparison.OrdinalIgnoreCase))
                    {
                        _cbTagValue.Text = existingValue;
                    }
                }
                ApplyTagChange();
            }
        }


        void _cbCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            _cbTagValue.Text = "";
            _cbTagValue.Items.Clear();
            if (_cbTagCategory.SelectedIndex != -1)
            {
                foreach (string value in TracyFacade.Instance.TagManager.GetValues(_cbTagCategory.SelectedItem.ToString()))
                {
                    _cbTagValue.Items.Add(value);
                }
                _cbTagValue.Focus();
            }
        }

        private void _btnAdd_Click(object sender, EventArgs e)
        {
            if (!IsTagEditing())
            {
                _editingTag = null;
                StartTagEditing(TagPanel.Controls.Count);
            }
            else
            {
                //Apply change
                ApplyTagChange();
            }
        }

        private bool IsTagEditing()
        {
            return _btnTagAdd.Text != "Add";
        }

        private void StartTagEditing(int labelIndex)
        {
            _btnTagAdd.Text = "Done";

            //Setup category selection
            _cbTagCategory.Items.Clear();
            List<string> categories = TracyFacade.Instance.TagManager.Categories;
            int currentIndex = -1;
            for (int i = 0; i < categories.Count; i++){
                string category = categories[i];
                if (_editingTag != null && category == _editingTag.Category) currentIndex = i;
                _cbTagCategory.Items.Add(category);
            }

            if (_editingTag != null)
            {
                //Editing tag
                if (currentIndex >= 0)
                {
                    _cbTagCategory.SelectedIndex = currentIndex;
                }
                else
                {
                    MessageBox.Show("Category not found: " + _editingTag.Category);
                }
            }
            else
            {
                //New Tag
                if (_cbTagCategory.Items.Count > 0)
                {
                    int selectIndex = 0;
                    for (int i = 0; i < _cbTagCategory.Items.Count; i++)
                    {
                        bool isCategoryExisting = false;
                        foreach (Tag existingTag in TracyFacade.Instance.TagManager.GetTags(GetSelectedEntry()))
                        {
                            if (existingTag.Category == _cbTagCategory.Items[i].ToString())
                            {
                                isCategoryExisting = true;
                                break;
                            }
                        }
                        if (!isCategoryExisting)//Select the first non-used category
                        {
                            selectIndex = i;
                            break;
                        }
                    }
                    _cbTagCategory.SelectedIndex = selectIndex;
                }

            }

            _cbTagCategory.DropDownStyle = ComboBoxStyle.DropDownList;
            TagPanel.Controls.Add(_cbTagCategory);
            TagPanel.Controls.SetChildIndex(_cbTagCategory, labelIndex);

            //Value box
            if (_editingTag != null) _cbTagValue.Text = _editingTag.Value;
            TagPanel.Controls.Add(_cbTagValue);
            TagPanel.Controls.SetChildIndex(_cbTagValue, labelIndex + 1);
            _cbTagValue.SelectAll();
            _cbTagValue.Focus();
            //Set button index
            TagPanel.Controls.SetChildIndex(_btnTagAdd, labelIndex + 2);
        }

        private void ApplyTagChange()
        {
            _btnTagAdd.Text = "Add";
            int index = TagPanel.Controls.IndexOf(_cbTagCategory);
            TagPanel.Controls.Remove(_cbTagCategory);
            TagPanel.Controls.Remove(_cbTagValue);
            Entry entry = GetSelectedEntry();
            Tag tag = null;
            if (!String.IsNullOrEmpty(_cbTagValue.Text))
            {
                tag = new Tag() { Category = _cbTagCategory.SelectedItem.ToString(), Value = _cbTagValue.Text };    
            }

            bool changed = ((tag != null && _editingTag == null) || 
                            (tag == null && _editingTag != null) ||
                            (tag != null && _editingTag != null && (tag.Category != _editingTag.Category || tag.Value != _editingTag.Value)));

            if (tag != null)//not remove mode
            {
                DisplayTag(tag, index);
                if(changed) 
                    TracyFacade.Instance.TagManager.AssignTag(entry, tag);
            }
            
            //set button index
            TagPanel.Controls.SetChildIndex(_btnTagAdd, TagPanel.Controls.Count - 1);

            
            if (_editingTag != null)
            {
                //edit mode or remove mode
                if (changed) 
                    TracyFacade.Instance.TagManager.RemoveTag(entry, _editingTag); 
                _editingTag = null;
            }

            if (changed) _ueEntry.UpdateTreeForItemChange(entry);
        }



        private void DisplayTag(Tag tag, int index)
        {
            TextBox lbTag = new TextBox();
            lbTag.ReadOnly = true;
            lbTag.BorderStyle = BorderStyle.None;
            lbTag.Text = tag.Category + ": " + tag.Value;
            lbTag.AutoSize = true;
            lbTag.Tag = tag;
            lbTag.MouseDoubleClick += new MouseEventHandler(lbTag_MouseDoubleClick);
            TagPanel.Controls.Add(lbTag);
            TagPanel.Controls.SetChildIndex(lbTag, index);
            //Label lbCategory = new Label();
            //lbCategory.Text = tag.Category + ": ";
            //TagPanel.Controls.Add(lbCategory);

            //Label lbValue = new Label();
            //lbValue.Text = tag.Value;
            //TagPanel.Controls.Add(lbValue);
            //TagPanel.SetFlowBreak(lbValue, true);
        }

        void lbTag_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (sender is TextBox)
            {
                TextBox l = (TextBox)sender;
                Tag tag = l.Tag as Tag;
                if (tag != null)
                {
                    if (IsTagEditing()) ApplyTagChange();//Apply change before new editing
                    int index = TagPanel.Controls.IndexOf(l);
                    TagPanel.Controls.Remove(l);
                    _editingTag = tag;
                    StartTagEditing(index);
                }
            }
        }

        private void ShowTagPanel(Entry entry)
        {
            _selectedEntryPage.TagPanelCollapsed = false;
            TagPanel.Controls.Clear();
            foreach (Tag tag in TracyFacade.Instance.TagManager.GetTags(entry))
            {
                DisplayTag(tag, TagPanel.Controls.Count);
            }
            TagPanel.Controls.Add(_btnTagAdd);
            
        }
    }
}
